package com.wendy.admin.controller;

import com.wendy.admin.api.domain.LoginSysUser;
import com.wendy.admin.api.model.LoginUser;
import com.wendy.admin.domain.bo.SysDeptBo;
import com.wendy.admin.domain.bo.SysUserBo;
import com.wendy.admin.domain.vo.SysUserExcelVo;
import com.wendy.admin.domain.vo.SysUserVo;
import com.wendy.admin.domain.vo.TreeSelect;
import com.wendy.admin.entity.SysRole;
import com.wendy.admin.entity.SysUser;
import com.wendy.admin.service.*;
import com.wendy.common.core.domain.TableDataInfo;
import com.wendy.common.core.errcode.user.UserError;
import com.wendy.common.core.utils.StringUtils;
import com.wendy.common.log.annotation.Log;
import com.wendy.common.log.enums.BusinessType;
import com.wendy.common.web.controller.BaseController;
import com.wendy.config.api.RemoteConfigService;
import com.wendy.custom.security.annotation.InnerAuth;
import com.wendy.custom.security.annotation.RequiresPermissions;
import com.wendy.custom.security.utils.SecurityUtils;
import com.wendy.excel.ruoyi.utils.ExcelUtil;
import com.wendy.utils.spring.MapstructUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author wendy
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private RemoteConfigService configService;

    /**
     * 获取用户列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/page")
    public TableDataInfo page(SysUserBo user) {
        TableDataInfo<SysUserVo> list = userService.selectUserPage(user);
        return list;
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUserBo user) {
        List<SysUser> list = userService.selectUserList(user);
        List<SysUserExcelVo> resultList = MapstructUtils.convert(list, SysUserExcelVo.class);
        ExcelUtil<SysUserExcelVo> util = new ExcelUtil<SysUserExcelVo>(SysUserExcelVo.class);
        util.exportExcel(response, resultList, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    public String importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUserExcelVo> util = new ExcelUtil<SysUserExcelVo>(SysUserExcelVo.class);
        List<SysUserExcelVo> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        List<SysUserBo> resultList = MapstructUtils.convert(userList, SysUserBo.class);
        String message = userService.importUser(resultList, updateSupport, operName);
        return message;
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysUserExcelVo> util = new ExcelUtil<SysUserExcelVo>(SysUserExcelVo.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{username}")
    public LoginUser info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            UserError.NAME_OR_PASSWORD_ERROR.fire();
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(MapstructUtils.convert(sysUser, LoginSysUser.class));
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return sysUserVo;
    }

    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    public Boolean register(@RequestBody SysUser sysUser) {
        String username = sysUser.getUserName();
        if (!("true".equals(configService.getConfigKey("sys.account.registerUser")))) {
            UserError.USER_MOBILE_ALREADY_EXIST.formatFire(username);
        }
        if (!userService.checkUserNameUnique(sysUser)) {
            UserError.USER_EMAIL_ALREADY_EXIST.formatFire(username);
        }
        return userService.registerUser(sysUser);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public Map<String,Object> getInfo() {
        SysUser user = userService.selectUserById(SecurityUtils.getUserId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Map<String,Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @RequiresPermissions("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public Map<String, Object> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        Map<String, Object> ajax = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put("user", sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public int add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            UserError.USER_ALREADY_EXIST.formatFire(user.getUserName());
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            UserError.USER_MOBILE_ALREADY_EXIST.formatFire(user.getUserName());
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            UserError.USER_EMAIL_ALREADY_EXIST.formatFire(user.getUserName());
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return userService.insertUser(user);
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public int edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            UserError.EDIT_USER_ALREADY_EXIST.formatFire(user.getUserName());
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            UserError.EDIT_USER_MOBILE_ALREADY_EXIST.formatFire(user.getUserName());
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            UserError.EDIT_USER_EMAIL_ALREADY_EXIST.formatFire(user.getUserName());
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return userService.updateUser(user);
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public int remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            UserError.CAN_NOT_DEL.fire();
        }
        return userService.deleteUserByIds(userIds);
    }

    /**
     * 重置密码
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public int resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return userService.resetPwd(user);
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public int changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return userService.updateUserStatus(user);
    }

    /**
     * 根据用户编号获取授权角色
     */
    @RequiresPermissions("system:user:query")
    @GetMapping("/authRole/{userId}")
    public Map<String, Object> authRole(@PathVariable("userId") Long userId) {
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("user", user);
        resultMap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return resultMap;
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public boolean insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return true;
    }

    /**
     * 获取部门树列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/deptTree")
    public List<TreeSelect> deptTree(SysDeptBo dept) {
        return deptService.selectDeptTreeList(dept);
    }
}
